<template>
  <div id="JorLibraryDet">
    <div style="display: flex">
      <el-scrollbar>
        <div class="left-tree">
          <div class="careeTree">
            <div class="careeTreeHead f14">全部职业</div>
            <el-tree
              empty-text="暂无数据"
              v-loading="treeLoading"
              style="max-width: 260px"
              :data="treeData"
              node-key="code"
              :default-expanded-keys="expandedKeys"
              :props="defaultProps"
              ref="treeRef"
            >
              <template #default="{ node, data }">
                <div
                  @click="handleTreeName(node, data)"
                  class="custom-tree-node"
                  :class="{
                    treeActive: isTreeActive(node),
                  }"
                >
                  {{ node.data.name }}
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-scrollbar>
      <el-scrollbar class="right-contaier">
        <div>
          <div class="like-box df">
            <div class="left">
              <h1>
                {{
                  get(jorPorpData, 'name', get(jorPorpData, 'jobName', '-'))
                }}({{
                  get(jorPorpData, 'code', get(jorPorpData, 'jobCode', '-'))
                }})
              </h1>
              <div class="df">
                <div
                  class="mt15 f14"
                  style="color: #999"
                  v-for="(item, index) in foundItem"
                  :key="item.name"
                >
                  {{ item.name }}
                  <span
                    v-if="index !== foundItem.length - 1"
                    style="margin: 0 5px"
                  >
                    >
                  </span>
                </div>
              </div>
            </div>
          </div>
          <!-- v-if="!isChildrenJorShow" -->
          <div class="tabs-box" style="margin-top: 20px">
            <div class="tabs">
              <el-tabs v-model="activeName" class="demo-tabs">
                <el-tab-pane
                  :label="isMyShowType == 2 ? '岗位概述' : '职业概述'"
                  name="zhiyegaishu"
                >
                  <div
                    v-if="isMyShowType != 2"
                    :style="isShow ? 'height:150px' : 'height:100%'"
                    style="
                      /* height: 150px; */
                      overflow: hidden;
                      position: relative;
                      margin-top: 30px;
                    "
                  >
                    <div
                      v-html="jorDetailsData.desc"
                      style="color: #666; white-space: pre-wrap"
                      class="desc f14"
                    ></div>
                    <div
                      class="read-more"
                      v-show="isShow"
                      @click="handleRedaMore"
                    >
                      阅读更多
                    </div>
                    <div
                      v-show="!isShow"
                      class="curr"
                      style="text-align: center; margin-top: 20px"
                      @click="handleRedaMore"
                    >
                      收起
                    </div>
                  </div>

                  <div class="imgBox" v-show="isShow">
                    <div class="num">
                      <el-statistic :value="outputValue" />
                      <span>份</span>
                    </div>
                  </div>

                  <div v-show="isShow">
                    <div>
                      <div><mytitlebar title="专业要求" /></div>
                      <div class="df" style="justify-content: space-between">
                        <div style="width: 45%">
                          <careertable
                            :careerTableData="firstMajor"
                            :title="majorTitle"
                            :type="1"
                            @goMajorlibrary="goMajorlibrary"
                          />
                        </div>
                        <div style="width: 45%">
                          <careertable
                            :careerTableData="twoMajor"
                            :title="majorTitle"
                            :type="1"
                            @goMajorlibrary="goMajorlibrary"
                          />
                        </div>
                      </div>
                    </div>

                    <div>
                      <div><mytitlebar title="学历要求" /></div>
                      <div class="df" style="justify-content: space-between">
                        <picChart :eduNeed="jorDetailsData.eduNeed" />
                        <barChart :eduNeed="jorDetailsData.eduNeed" />
                      </div>
                    </div>

                    <div>
                      <div><mytitlebar title="人才需求" /></div>
                      <div style="margin: 20px 0 10px 0">各省市招聘统计</div>
                      <div class="df" style="justify-content: space-between">
                        <div style="width: 45%">
                          <careertable
                            :careerTableData="firstPro"
                            :title="porTitle"
                            :type="2"
                          />
                        </div>
                        <div style="width: 45%">
                          <careertable
                            :careerTableData="twoPro"
                            :title="porTitle"
                            :type="2"
                          />
                        </div>
                      </div>
                    </div>

                    <div>
                      <div><mytitlebar title="招聘企业" /></div>
                      <div
                        class="df"
                        style="justify-content: space-between; width: 100%"
                      >
                        <div style="width: 45%">
                          <div style="margin: 20px 0 10px 0">招聘企业类型</div>
                          <div>
                            <careertable
                              :careerTableData="
                                jorDetailsData.companyType || []
                              "
                              :type="3"
                            />
                          </div>
                        </div>

                        <div style="width: 45%">
                          <div style="margin: 20px 0 10px 0">优质招聘企业</div>
                          <careertable
                            :careerTableData="jorDetailsData.companyFine || []"
                            :type="4"
                          />
                        </div>
                      </div>
                    </div>
                    <div class="f12" style="margin-top: 20px">
                      招聘数据来自国家大学生就业服务平台及各大招聘平台
                    </div>
                  </div>
                </el-tab-pane>
                <el-tab-pane
                  label="就业岗位"
                  name="jiuyegangwei"
                  v-if="isMyShowType != 2"
                >
                  <careertable
                    :careerTableData="jboPositionData"
                    :type="5"
                    @goZhiYe="goZhiYe"
                  />
                </el-tab-pane>
                <el-tab-pane label="企业招聘" name="qiyezhaopin">
                  <enterprise-recruitment
                    :jobCompanyData="jobCompanyData"
                    v-loading="loading"
                    v-infinite-scroll="nextPage"
                    :infinite-scroll-immediate="false"
                    :infinite-scroll-delay="500"
                    :infinite-scroll-disabled="lastpage && !loading"
                  />
                </el-tab-pane>
                <el-tab-pane
                  v-if="isMyShowType != 2"
                  label="人才培养院校"
                  name="rencaipeiyangyuanxiao"
                >
                  <schoolDate
                    ref="schoolDateinfo"
                    :studentId="studentId"
                    :storeType="2"
                  ></schoolDate>
                  <div class="table-box" style="margin-top: 20px">
                    <el-table
                      :data="rencaiTableData"
                      style="width: 100%"
                      stripe
                    >
                      <el-table-column prop="rank" label="专业排名" />
                      <el-table-column label="院校信息" width="300">
                        <template #default="scope">
                          <div style="font-weight: bold">
                            {{ scope.row.cnName || '-' }}
                          </div>
                          <span
                            class="f12"
                            v-for="item in JSON.parse(scope.row.features)"
                            :key="item"
                            >{{ item }}</span
                          >
                        </template>
                      </el-table-column>
                      <el-table-column prop="address" label="所在地">
                        <template #default="scope">
                          {{ get(scope.row, 'provinceName', '-') }}&nbsp;{{
                            get(scope.row, 'cityName', '-')
                          }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="natureTypeName" label="性质">
                        <template #default="scope">
                          {{ natureTypeName(scope.row.natureType) }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="belong" label="类型">
                        <template #default="scope">
                          {{ JSON.parse(scope.row.categories)[0] || '-' }}
                        </template>
                      </el-table-column>
                      <el-table-column prop="hits" label="报考热度">
                        <template #default="scope">
                          {{ formatHits(scope.row.hits) }}
                        </template>
                      </el-table-column>
                    </el-table>
                    <div style="margin: 30px 0">
                      <el-pagination
                        :current-page="requestData.page"
                        :page-size="requestData.pageSize"
                        :page-sizes="[10, 20, 30]"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                      />
                    </div>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import {
  getAllCareer,
  getCareerDetail,
  getCareerJobPosition,
  getCareerJobCompany,
  careerSchool,
} from '@/api/appv2/appv2';

import enterpriseRecruitment from '../EnterpriseRecruitment';
import schoolDate from '@/views/leader/volunteer/module/schoolDate.vue'; // 学校
import userSearch from '@/store/modules/searchInfoMajorTool.js';
import mytitlebar from '../MyTitleBar.vue';
import careertable from '../CareerTable.vue';
import picChart from '../PicChart.vue';
import barChart from '../BarChart.vue';
import { useTransition } from '@vueuse/core';
import { get } from 'lodash';
const emit = defineEmits(['goMajorlibrary']);
const goMajorlibrary = (data) => {
  emit('goMajorlibrary', data);
};

const isMyShowType = ref('');
const treeRef = ref(null);

const jobCompanyData = ref([]);

const total = ref(0);
const majorTitle = ref(['排位', '专业名称', '专业占比', '趋势']);
const porTitle = ref(['排位', '省份', '招聘人数', '占比', '薪资范围']);
const defaultProps = {
  children: 'children',
  label: 'name',
};
const isShow = ref(true);
const sorce = ref(0);

const studentId = ref(localStorage.getItem('student_id') * 1);
const rencaiTableData = ref([]);
// 请求数据
const requestData = reactive({
  studentId: localStorage.getItem('student_id') * 1,
  batch: '',
  page: 1,
  code: '',
  pageSize: 10,
  fronttype: 3,
  fType: 0, // 0-全部
  hasZJ: 0, // 0-全部
  order: '', // 排序 chance-录取率 rank-院校排名 planNum-招生计划
  is_sort: false, // 是否升序，false升序，true降序
});
const screenData = ref({}); // 筛选数据
const userSearchVal = userSearch(); // 筛选仓库
let userSearchDate = computed(() => userSearchVal.searchArraylist); // 筛选数据
watch(
  // 监听院校筛选数据改变
  () => userSearchDate.value,
  () => {
    requestData.page = 1;
    schoolSearchDataChange();
  }
);
// 院校筛选数据改变
function schoolSearchDataChange() {
  let searchData = {
    province: [],
    categories: [],
    features: [],
    natureType: [],
    eduLevelSchool: [],
    schoolNewly: [],
    scode: [],
    mcode: [],
    zcode: [],
    ssearch: '',
    msearch: '',
    zsearch: '',
  };

  for (let item of userSearchDate.value) {
    switch (item.type) {
      case 'province':
        searchData.province.push(item.code);
        break;
      case 'type':
        searchData.categories.push(item.code);
        break;
      case 'school_feature':
        searchData.features.push(item.code);
        break;
      case 'nature':
        searchData.natureType.push(item.code);
        break;
      case 'school_type':
        searchData.eduLevelSchool.push(item.code);
        break;
      case 'schoolNewly':
        searchData.schoolNewly.push(item.code);
        break;
      case 'schoolSearch':
        searchData.scode.push(item.code);
        break;
      case 'major':
        searchData.mcode.push(item.code);
        break;
      case 'job':
        searchData.zcode.push(item.code);
        break;
      case 'ssearch':
        searchData.ssearch = item.name;
        break;
      case 'msearch':
        searchData.msearch = item.name;
        break;
      case 'zsearch':
        searchData.zsearch = item.name;
    }
  }

  let data = {
    province: searchData.province.toString(),
    categories: searchData.categories.toString(),
    features: searchData.features.toString(),
    natureType: searchData.natureType.toString(),
    eduLevelSchool: searchData.eduLevelSchool.toString(),
    schoolNewly: searchData.schoolNewly.toString(),
    scode: searchData.scode.toString(),
    mcode: searchData.mcode.toString(),
    zcode: searchData.zcode.toString(),
    ssearch: searchData.ssearch,
    msearch: searchData.msearch,
    zsearch: searchData.zsearch,
  };
  screenData.value = data;
  fetchSearchMajorSchool();
}
const fetchSearchMajorSchool = () => {
  let data = {
    ...requestData,
    ...screenData.value,
  };
  data['zy_type'] = 3;
  careerSchool(data).then((res) => {
    if (res.code == 20000) {
      rencaiTableData.value = res.data.data;
      total.value = res.data.total;
    }
  });
};

const natureTypeName = (val) => {
  switch (val) {
    case 'public':
      return '公办';
    case 'private':
      return '民办';
    case 'aw_ga':
      return '中外/港澳';
  }
};

const handleSizeChange = (val) => {
  requestData.pageSize = val;
  fetchSearchMajorSchool();
};
const handleCurrentChange = (val) => {
  requestData.page = val;
  fetchSearchMajorSchool();
};

const treeData = ref([]);
const firstMajor = ref([]);
const twoMajor = ref([]);
const firstPro = ref([]);
const twoPro = ref([]);
const jorDetailsData = ref({});
const foundItem = ref([]);
const activeName = ref('zhiyegaishu');

const expandedKeys = ref([]);
const jorPorpData = ref({});
const treeLoading = ref(false);
// 处理热度展示
const formatHits = (hits) => {
  if (isNaN(hits)) {
    return '0万'; // 防止数据异常
  }
  return new Intl.NumberFormat('en-US').format(hits) + '万';
};

const goZhiYe = (item) => {
  let treeDataCopy = JSON.parse(JSON.stringify(treeData.value));
  isMyShowType.value = 2;
  activeName.value = 'zhiyegaishu';
  jorPorpData.value.code = item.postCode;
  jorPorpData.value.name = item.postName;
  jorPorpData.value.level = 3;
  treeData.value = treeDataCopy;
  expandedKeys.value = [item.postCode];
  fetchCareerDetail();
  fetchCareerJobPosition();
  fetchCareerJobCompany();
  if (jorPorpData.value.code) {
    foundItem.value = handleFindItem(
      JSON.parse(JSON.stringify(treeData.value)),
      jorPorpData.value.code
    );
  } else {
    foundItem.value = handleFindItem(
      JSON.parse(JSON.stringify(treeData.value)),
      jorPorpData.value.jobCode
    );
  }
};

const handleTreeName = (node, data) => {
  requData.value.page = 1;
  jobCompanyData.value = [];
  let type = 0;
  if (node.level == 1) {
    return;
  } else {
    if (node.level == 2) {
      type = '1';
    } else if (node.level == 3) {
      type = '2';
      activeName.value =
        activeName.value == 'jiuyegangwei' ? 'zhiyegaishu' : activeName.value;
    }
    handleInitMethod(data, type, false);
  }
};
const handleRedaMore = () => {
  isShow.value = !isShow.value;
};
const fetchAllCareer = () => {
  treeLoading.value = true;
  getAllCareer({ deep: 3 })
    .then((res) => {
      if (res.code == 20000) {
        treeLoading.value = false;
        treeData.value = res.data;
        if (jorPorpData.value.code) {
          foundItem.value = handleFindItem(
            JSON.parse(JSON.stringify(treeData.value)),
            jorPorpData.value.code
          );
        } else {
          foundItem.value = handleFindItem(
            JSON.parse(JSON.stringify(treeData.value)),
            jorPorpData.value.jobCode
          );
        }
      } else {
        treeLoading.value = false;
      }
    })
    .catch(() => {
      treeLoading.value = false;
    });
};
fetchAllCareer();
const lastpage = ref(false);
// 定义方法来检查激活状态
const isTreeActive = (node) =>
  [jorPorpData.value.code, jorPorpData.value.jobCode].includes(node.data.code);
const requData = ref({
  page: 1,
  pageSize: 30,
});
const loading = ref(false);
const nextPage = () => {
  if (activeName.value == 'qiyezhaopin') {
    requData.value.page += 1;
    fetchCareerJobCompany();
  }
};
const fetchCareerJobCompany = () => {
  requData.value.code = get(
    jorPorpData.value,
    'code',
    jorPorpData.value.jobCode
  );
  loading.value = true;
  getCareerJobCompany(requData.value)
    .then((res) => {
      if (res.code == 20000) {
        // 接口根本没有这个字断
        total.value = res.total || 0;
        if (res.data.length < requData.value.pageSize) {
          loading.value = false;
          lastpage.value = true;
        }
        jobCompanyData.value = [...jobCompanyData.value, ...res.data];
        loading.value = false;
        jobCompanyData.value?.forEach((v) => {
          v.publishAt = v.publishAt.split('T')[0];
        });
      } else {
        loading.value = false;
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

const fetchCareerDetail = () => {
  getCareerDetail({
    code: get(jorPorpData.value, 'code', jorPorpData.value.jobCode),
  }).then((res) => {
    if (res.code == 20000) {
      jorDetailsData.value = res.data;
      sorce.value = get(jorDetailsData.value, 'value', 0);

      const { majorNeed = [], demandNeed = [] } = get(res, 'data', '{}');
      majorNeed.forEach((item, index) => {
        item.index = index;
      });
      demandNeed?.forEach((item, index) => {
        item.index = index;
      });
      firstMajor.value = majorNeed?.slice(0, 5);
      twoMajor.value = majorNeed?.slice(5, 10);
      firstPro.value = demandNeed?.slice(0, 5);
      twoPro.value = demandNeed?.slice(5, 10);
      // 获取人才培养院校列表
      requestData.code = jorPorpData.value.code || jorPorpData.value.jobCode;
      fetchSearchMajorSchool();
    }
  });
};

// 数字计步器
const outputValue = useTransition(sorce, {
  duration: 1500,
});
// 使用 find() 方法查找匹配的数据项
const handleFindItem = (data, targetCode) => {
  const search = (data, targetCode, path) => {
    for (const item of data) {
      // 如果找到匹配项，则返回路径中的项
      if (item.code === targetCode) {
        return [...path, item];
      }
      // 如果有子项，则递归搜索
      if (item.children && item.children.length > 0) {
        const foundInChildren = search(item.children, targetCode, [
          ...path,
          item,
        ]);
        if (foundInChildren) {
          return foundInChildren;
        }
      }
    }
    // 如果未找到匹配项，则返回 null
    return null;
  };

  // 从根级数据开始搜索
  const pathToItem = search(data, targetCode, []);
  // 如果找到了目标项，则只返回目标项及其父级，不包含其他子项
  if (pathToItem) {
    const [targetItem, ...parents] = pathToItem;
    return [targetItem, ...parents];
  } else {
    return null;
  }
};
// 职业相关岗位
const jboPositionData = ref([]);
const fetchCareerJobPosition = () => {
  getCareerJobPosition({
    code: jorPorpData.value.code || jorPorpData.value.jobCode,
  }).then((res) => {
    if (res.code == 20000) {
      jboPositionData.value = res.data;
    }
  });
};

const handleInitMethod = (data, isShowType, fromOther = true) => {
  if (fromOther) {
    const allNodes = treeRef.value.store._getAllNodes();
    allNodes.forEach((item) => {
      item.expanded = false;
    });
    expandedKeys.value = [];
  }

  isMyShowType.value = isShowType;
  jorPorpData.value = data;
  expandedKeys.value.push(jorPorpData.value.code || jorPorpData.value.jobCode);
  fetchCareerDetail();
  fetchCareerJobPosition();
  fetchCareerJobCompany();
  if (jorPorpData.value.code) {
    foundItem.value = handleFindItem(
      JSON.parse(JSON.stringify(treeData.value)),
      jorPorpData.value.code
    );
  } else {
    foundItem.value = handleFindItem(
      JSON.parse(JSON.stringify(treeData.value)),
      jorPorpData.value.jobCode
    );
  }
};
defineExpose({
  handleInitMethod,
});
</script>

<style lang="scss" scoped>
// margin-bottom: 300px;
.imgBox {
  width: 100%;
  height: 120px;
  margin-top: 10px;
  background-image: url('@/assets/images/imgBox.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  .num {
    padding-top: 70px;
    width: 100%;
    height: 42px;
    line-height: 42px;
    text-align: center;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
  }
}
.left-tree {
  // width: 260px;
  padding-right: 50px;
  margin-right: 30px;
  border: 1px solid #f2f2f2;
  height: calc(100vh - 155px);
  .careeTreeHead {
    padding: 10px;
    border-bottom: 1px solid #f2f2f2;
  }
}
.right-contaier {
  height: calc(100vh - 155px);
  flex: 1;
  .like-box {
    padding: 15px;
    height: 100%;
    background: #f5f9ff;
    justify-content: space-between;
  }
}
.treeActive {
  color: #409eff;
}
.read-more {
  position: absolute;
  top: 70px;
  left: 0;
  width: 100%;
  height: 80px;
  background: linear-gradient(180deg, hsla(0, 0%, 100%, 0), #fff 60%, #fff);
  text-align: center;
  line-height: 36px;
  color: #333;
  font-size: 14px;
  padding-top: 50px;
  cursor: pointer;
}
.tabs-box {
  :deep(.el-tabs__active-bar) {
    height: 0px !important;
  }
  :deep(.el-tabs__nav-wrap::after) {
    content: '';
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 1px;
    background-color: #409eff;
    z-index: var(--el-index-normal);
  }
  :deep(.is-active) {
    background: #409eff;
    color: #fff;
    border-radius: 4px;
  }
  :deep(.el-tabs__item) {
    padding: 0 30px !important;
  }
}
</style>
